package com.example.hotel_lxy.ui.fragment;


import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hotel_lxy.R;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.FOrderAllBean;
import com.example.hotel_lxy.bean.PendingSevenBean;
import com.example.hotel_lxy.bean.RvStandardTypeBean;
import com.example.hotel_lxy.bean.ScheduledBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.activity.ReserveActivity;
import com.example.hotel_lxy.ui.activity.ReserveInformationActivity;
import com.example.hotel_lxy.ui.activity.SetUpZeroPointReserveActivity;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialog;
import com.example.hotel_lxy.ui.dialog.DialPhoneDialog;
import com.example.hotel_lxy.ui.dialog.StoreDateDialog;
import com.example.hotel_lxy.ui.main.CalendarOrderActivity;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.EmptyUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.google.android.material.tabs.TabLayout;
import com.luck.picture.lib.tools.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ysxsoft.common_base.adapter.BaseQuickAdapter;
import com.ysxsoft.common_base.adapter.BaseViewHolder;
import com.ysxsoft.common_base.base.BaseFragment;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.base.frame.list.IListAdapter;
import com.ysxsoft.common_base.base.frame.list.ListManager;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.view.widgets.MultipleStatusView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/***
 *
 * 待处理
 *
 */
public class FragmentPending extends BaseFragment implements IListAdapter<PendingSevenBean.DataBean.ListBean> {
    @BindView(R.id.tabs_pending)
    TabLayout tabsPending;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.text_pending_office)
    TextView textPendingOffice;
    @BindView(R.id.text_pending_type)
    TextView textPendingType;

    private List<String> mTitles_pending = new ArrayList<>();
    ListManager<PendingSevenBean.DataBean.ListBean> manager;
    private String day="1";
    private String tid="";
    private String bid="";
    private String director_id="";
    private List<Officetype> pop_mlist_office = new ArrayList<>();
    private List<Officetype> pop_mlist_type = new ArrayList<>();
    private PopupWindow mpopup_pending_office;
    private PopupWindow mpopup_pending_type;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_pending;
    }


    @Override
    protected void doWork(View view) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);  //事件的注册
        }else{
            EventBus.getDefault().unregister(this); //解除注册
            EventBus.getDefault().register(this);  //事件的注册
        }
        String string = SPUtils.get(getContext(), "id", "").toString();
        director_id = string + "";
        ShowData();
        showView(view);
        //宴会厅
        showOffice();
        showOfficeType();
    }
    private void showView(View view) {
        manager = new ListManager(this);
        manager.init(view);
        manager.getAdapter().setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        manager.getAdapter().setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                request(manager.nextPage());
            }
        }, recyclerView);


    }
    private void showOffice() {
        OkHttpUtils.post()
                .url(Api.POST_INDEX_SCHEDULED)
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "宴会厅onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "宴会厅onResponse   " + response);
                        if(response.equals("")){
                            return;
                        }
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(getContext(),"token","");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ScheduledBean scheduledBean = JsonUtils.parseByGson(response, ScheduledBean.class);
                        Officetype officetype1 = new Officetype();
                        officetype1.setId("0");
                        officetype1.setName("全部");
                        pop_mlist_office.add(officetype1);
                        for (int i = 0; i < scheduledBean.getData().size(); i++) {
                            Officetype officetype = new Officetype();
                            officetype.setId(scheduledBean.getData().get(i).getId() + "");
                            officetype.setName(scheduledBean.getData().get(i).getName());
                            pop_mlist_office.add(officetype);
                        }
                    }
                });
    }
    private void showOfficeType() {
        pop_mlist_type.clear();
        OkHttpUtils.post()
                .url(Api.POST_SCHEDULED_TYPE)
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "获取宴会厅的类型onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "获取宴会厅的类型onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(getContext(),"token","");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        RvStandardTypeBean rvStandardTypeBean = JsonUtils.parseByGson(response, RvStandardTypeBean.class);
                        Officetype officetype1 = new Officetype();
                        officetype1.setId("0");
                        officetype1.setName("全部");
                        pop_mlist_type.add(officetype1);
                        if (beanBean.getCode().equals("0")) {
                            for (int i = 0; i < rvStandardTypeBean.getData().getType().size(); i++) {
                                RvStandardTypeBean.DataBean.TypeBean typeBean = rvStandardTypeBean.getData().getType().get(i);
                                Officetype officetype = new Officetype();
                                officetype.setId(typeBean.getId() + "");
                                officetype.setName(typeBean.getName());
                                pop_mlist_type.add(officetype);
                            }
                        }
                    }
                });
    }
    private void ShowData() {
        mTitles_pending.add("近7天");
        mTitles_pending.add("近30天");
        mTitles_pending.add("近90天");
        for (String title : mTitles_pending) {
            tabsPending.addTab(tabsPending.newTab().setText(title));
        }

        tabsPending.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (EmptyUtils.isNotEmpty(position)) {
                    switch (position) {
                        case 0:
                            day = "1";
                            request(1);
                            break;
                        case 1:
                            day = "2";
                            request(1);
                            break;
                        case 2:
                            day = "3";
                            request(1);
                            break;

                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public int getItemLayoutId() {
        return R.layout.item_order_rv_info;
    }

    @Override
    public void request(int page) {
        showLoadingDialog();
        OkHttpUtils.post()
                .url(Api.POST_PENDING)
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .addParams("day", day + "")
                .addParams("tid", tid)
                .addParams("bid", bid)
                .addParams("director_id", director_id)
                .addParams("page", ""+page)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "待处理订单onError   " + e.getMessage());
                        ToastUtils.s(getContext(),""+e.getMessage());
                        manager.releaseRefresh();
                        hideLoadingDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "待处理订单onResponse   " + response);
                        manager.releaseRefresh();
                        hideLoadingDialog();
                        BeanBean beanBean = JsonUtils.parseObject(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            PendingSevenBean pendingSevenBean = JsonUtils.parseObject(response, PendingSevenBean.class);
                            if(page==1){
                                manager.resetPage();
                            }
                            manager.setData(pendingSevenBean.getData().getList());
                        }else if(beanBean.getCode().equals("4")){
                            SPUtils.put(getContext(),"token","");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                    }
                });
    }


    @Override
    public void fillView(BaseViewHolder holder, PendingSevenBean.DataBean.ListBean item) {
        TextView text_date = holder.itemView.findViewById(R.id.text_date);
        TextView text_office = holder.itemView.findViewById(R.id.text_office);
        TextView text_user_name = holder.itemView.findViewById(R.id.text_user_name);
        TextView text_type = holder.itemView.findViewById(R.id.text_type);
        TextView text_phone = holder.itemView.findViewById(R.id.text_phone);
        String[] split = item.getBegin().split(" ");
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        String currentDate = simpleDateFormat.format(date);
        long stringToDate = getStringToDate(split[0]);
        long l =getStringToDate(currentDate);

        if (stringToDate==l) {
            if(day.equals("1")){
                text_date.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_office.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_user_name.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_type.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_phone.setTextColor(getResources().getColor(R.color.color_FF1200));
//                if(item.getBegin_night()==1){
//                    DateFormat simpleDateFormats = new SimpleDateFormat("HH:mm");
//                    Date dates = new Date(System.currentTimeMillis());//获取当前时间
//                    String currentDates = simpleDateFormats.format(dates);
//                    String time = "00:00-" + currentDates;
//                    String[] two = time.split("-");
//                    String[] second = two[1].split(":");
//                    int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
//                    if (secondTotalMinute > 960) {
//                        text_date.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_office.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_user_name.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_type.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_phone.setTextColor(getResources().getColor(R.color.color_FF1200));
//                    }
//                }
//                else if(item.getBegin_night()==1){
//                    DateFormat simpleDateFormats = new SimpleDateFormat("HH:mm");
//                    Date dates = new Date(System.currentTimeMillis());//获取当前时间
//                    String currentDates = simpleDateFormats.format(dates);
//                    String time = "00:00-" + currentDates;
//                    String[] two = time.split("-");
//                    String[] second = two[1].split(":");
//                    int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
//                    if (secondTotalMinute >= 960 && secondTotalMinute < 1380) {
//                        text_date.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_office.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_user_name.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_type.setTextColor(getResources().getColor(R.color.color_FF1200));
//                        text_phone.setTextColor(getResources().getColor(R.color.color_FF1200));
//                    }
//                }
            }
            else{
                text_date.setTextColor(getResources().getColor(R.color.color_010000));
                text_office.setTextColor(getResources().getColor(R.color.color_010000));
                text_user_name.setTextColor(getResources().getColor(R.color.color_010000));
                text_type.setTextColor(getResources().getColor(R.color.color_010000));
                text_phone.setTextColor(getResources().getColor(R.color.color_010000));
            }
        }
        else if(l>stringToDate){
            if(day.equals("1")){
                text_date.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_office.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_user_name.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_type.setTextColor(getResources().getColor(R.color.color_FF1200));
                text_phone.setTextColor(getResources().getColor(R.color.color_FF1200));
            } else{
                text_date.setTextColor(getResources().getColor(R.color.color_010000));
                text_office.setTextColor(getResources().getColor(R.color.color_010000));
                text_user_name.setTextColor(getResources().getColor(R.color.color_010000));
                text_type.setTextColor(getResources().getColor(R.color.color_010000));
                text_phone.setTextColor(getResources().getColor(R.color.color_010000));
            }
        }
        else{
            text_date.setTextColor(getResources().getColor(R.color.color_010000));
            text_office.setTextColor(getResources().getColor(R.color.color_010000));
            text_user_name.setTextColor(getResources().getColor(R.color.color_010000));
            text_type.setTextColor(getResources().getColor(R.color.color_010000));
            text_phone.setTextColor(getResources().getColor(R.color.color_010000));

        }
        if(item.getBegin_night()==2){
            if(item.getIs_meeting()==1){
                if(item.getBegin_night()==2){
                    text_date.setText("" + item.getBegin()+"\n下午");
                }else{
                    text_date.setText("" + item.getBegin()+"\n上午");
                }
            }else{
                text_date.setText("" + item.getBegin()+"\n晚上");
            }
        }else{
            if(item.getIs_meeting()==1){
                if(item.getBegin_night()==2){
                    text_date.setText("" + item.getBegin()+"\n下午");
                }else{
                    text_date.setText("" + item.getBegin()+"\n上午");
                }
            }else{
                text_date.setText("" + item.getBegin()+"\n中午");
            }
        }
        text_office.setText("" + item.getB_name());
        text_user_name.setText("" + item.getBook());
        text_type.setText("" + item.getT_name());
        text_phone.setText("" + item.getMobile());
        text_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DatePhotoUtils.isPhone(item.getMobile() + "")) {
                    DialPhoneDialog.show(getContext(),null,item.getMobile()+"");
                } else {
                    ToastUtils.s(getContext(), "手机号有误");
                }
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReserveInformationActivity.start(item.getId() + "", ""+item.getIs_del());
            }
        });
    }

    public static long getStringToDate(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try{
            date = dateFormat.parse(dateString);
        } catch(ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    @Override
    public void fillMuteView(BaseViewHolder helper, PendingSevenBean.DataBean.ListBean listBean) {

    }

    @Override
    public void attachActivity(AppCompatActivity activity) {

    }

    @Override
    public void dettachActivity() {

    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getContext());
    }

    @Override
    public boolean isMuteAdapter() {
        return false;
    }

    @Override
    public int[] getMuteTypes() {
        return new int[0];
    }

    @Override
    public int[] getMuteLayouts() {
        return new int[0];
    }

    public class Officetype {
        private String name;
        private String id;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }
    }

    @OnClick({ R.id.text_pending_office, R.id.text_pending_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_pending_office://待处理 宴会厅
                showPopwindowPendingOffice();
                break;
            case R.id.text_pending_type://待处理 类型
                showPopwindowPendingType();
                break;
        }
    }

    //待处理 类型
    private void showPopwindowPendingType() {
        View popview = getLayoutInflater().inflate(R.layout.item_popwindow, null);
        RecyclerView recyclerView = popview.findViewById(R.id.rv_pop_info);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        RBaseAdapter<Officetype> rBaseAdapterPendingType = new RBaseAdapter<Officetype>(getContext(),
                R.layout.item_item_popwindow, pop_mlist_type) {
            @Override
            protected void fillItem(RViewHolder holder, Officetype item, int position) {
                TextView text_title = holder.itemView.findViewById(R.id.text_title);
                text_title.setText(pop_mlist_type.get(position).name);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tid = item.getId();
                        request(1);
                        mpopup_pending_type.dismiss();
                    }
                });
            }

            @Override
            protected int getViewType(Officetype item, int position) {
                return 0;
            }
        };
        recyclerView.setAdapter(rBaseAdapterPendingType);
        mpopup_pending_type = new PopupWindow(popview, textPendingType.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        mpopup_pending_type.setOutsideTouchable(true);
        mpopup_pending_type.setFocusable(true);
        mpopup_pending_type.showAsDropDown(textPendingType);

    }

    //待处理 宴会厅
    private void showPopwindowPendingOffice() {
        View popview = getLayoutInflater().inflate(R.layout.item_popwindow, null);
        RecyclerView recyclerView = popview.findViewById(R.id.rv_pop_info);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        RBaseAdapter<Officetype> rBaseAdapterPendingOffice = new RBaseAdapter<Officetype>(getContext(), R.layout.item_item_popwindow, pop_mlist_office) {
            @Override
            protected void fillItem(RViewHolder holder,Officetype item, int position) {
                TextView text_title = holder.itemView.findViewById(R.id.text_title);
                text_title.setText(pop_mlist_office.get(position).getName());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bid = item.getId();
                        request(1);
                        mpopup_pending_office.dismiss();
                    }
                });
            }

            @Override
            protected int getViewType(Officetype item, int position) {
                return 0;
            }
        };
        recyclerView.setAdapter(rBaseAdapterPendingOffice);
        mpopup_pending_office = new PopupWindow(popview, textPendingOffice.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        mpopup_pending_office.setOutsideTouchable(true);
        mpopup_pending_office.setFocusable(true);
        mpopup_pending_office.showAsDropDown(textPendingOffice);

    }

    @Override
    public void onResume() {
        super.onResume();
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);  //事件的注册
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this); //解除注册
        }
    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        if (carrier != null) {
            if(carrier.getType()==7){
                if(carrier.getDid()!=null&&!carrier.getDid().equals("")){
                    director_id = carrier.getDid();
                }
            }
            request(1);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!EventBus.getDefault().isRegistered(this)) {
            if (hidden) {
                EventBus.getDefault().unregister(this); //解除注册
            } else {
                EventBus.getDefault().register(this);  //事件的注册
            }
        }else{
            EventBus.getDefault().unregister(this); //解除注册
        }
    }
}